package cn.tx.api.controller;

import cn.tx.api.common.SenseNebulaJsonDataBodyAttrParam;
import cn.tx.api.common.SenseNebulaJsonDataEventsAttrParam;
import cn.tx.api.common.SenseNebulaJsonDataFaceAttrParam;
import cn.tx.api.common.SenseNebulaJsonParam;
import cn.tx.result.Result;
import cn.tx.result.ResultUtil;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.*;

/**
 * 盒子摄像头对接
 */
@RestController
@RequestMapping("api/sense")
public class SenseNebulaController {

    private static final Logger logger = LoggerFactory.getLogger(SenseNebulaController.class);

    private static final String APP_HTTP_KEY = "12345678987654321";

    @GetMapping("/hello")
    public String hello(){
        return "ApiApplication-SenseNebulaController-sense-[sense/hello]-Hello ^_^";
    }

    /**
     * 接收数据
     * @param request
     * @param key
     * @param json
     * @param snaps
     * @param imgs
     * @param snapFrames
     * @param vehicleNumImgs
     * @return
     */
    @PostMapping("receives")
    public Result receives(HttpServletRequest request,
                           @RequestParam("key") String key,
                           @RequestParam("json") String json,
                           @RequestParam("snap") List<MultipartFile> snaps,
                           @RequestParam("img") List<MultipartFile> imgs,
                           @RequestParam("snap_frame") List<MultipartFile> snapFrames,
                           @RequestParam("vehicle_num_img") List<MultipartFile> vehicleNumImgs){


        logger.info("ApiApplication.SenseNebulaController.receives.ip:{},key:{},json:{}",request.getRemoteAddr(),key,json);

        Map map = showParams(request);
        if (map == null){
            logger.error("request里面参数个数为空");
            return ResultUtil.fail("HttpServletRequest 什么都没有参数测试!");
        }
        Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String, String> entry = entries.next();
            String keys = entry.getKey();
            String values = entry.getValue();
            logger.info("request 里面参数有:{},value:{}",keys,values);
        }

        //1、获取签名
        String httpKey = map.get("key").toString();
        //2、获取数据库签名&校验签名比对结果
        if (!httpKey.equals(APP_HTTP_KEY)){
            return ResultUtil.error("APP_SIGNATURE_ERROR");
        }

        if (snaps != null && snaps.size() > 0){
            snaps.forEach(snap -> {
                String snapFileName = snap.getOriginalFilename();
                logger.info("抓拍人脸图片名称/人体小图snaps:{}",snapFileName);
            });
        }
        if (imgs != null && imgs.size() > 0){
            imgs.forEach(img -> {
                String imgName = img.getOriginalFilename();
                logger.info("比中底库图片名称imgs:{}",imgName);
            });
        }
        if (snapFrames != null && snapFrames.size() > 0){
            snapFrames.forEach(snapFrame -> {
                String snapFrameName = snapFrame.getOriginalFilename();
                logger.info("人脸/人体小图对应的场景大图名称snapFrames:{}",snapFrameName);
            });
        }
        if (vehicleNumImgs != null && vehicleNumImgs.size() > 0){
            vehicleNumImgs.forEach(vehicleNumImg -> {
                String vehicleNumImgName = vehicleNumImg.getOriginalFilename();
                logger.info("车牌图片名称vehicleNumImgs:{}",vehicleNumImgName);
            });
        }


        SenseNebulaJsonParam senseNebulaJson = JSON.parseObject(json, SenseNebulaJsonParam.class);



        //3、处理业务数据
        SenseNebulaJsonDataFaceAttrParam faceAttr = senseNebulaJson.getData().getFace_attr();
        if (faceAttr != null){
            logger.info("人脸属性数据:{}",JSON.toJSON(faceAttr));
        }
        SenseNebulaJsonDataBodyAttrParam bodyAttr = senseNebulaJson.getData().getBody_attr();
        if (bodyAttr != null){
            logger.info("人体属性数据:{}",JSON.toJSON(bodyAttr));
        }

        SenseNebulaJsonDataEventsAttrParam eventsAttr = senseNebulaJson.getData().getEvents_attr();
        if (eventsAttr != null){
            logger.info("事件属性数据:{}",JSON.toJSON(eventsAttr));
        }

        return ResultUtil.success();
    }

    @PostMapping("upload")
    public Result upload(HttpServletRequest request,
                           @RequestParam("sign") String sign,
                           @RequestBody String data){
        SenseNebulaJsonParam lbsData = JSON.parseObject(data, SenseNebulaJsonParam.class);

        //1、校验签名
        String appKey = "" ;//lbsData.getAppKey();

        //2、获取数据库是否签名是否存在
        //Project project = projectServiceRemote.queryProjectByAppKey(appKey);
        //  if (project == null){
        //  return ResultVoWrapper.buildFail(ParamErrorCode.QUERY_DATA_PROJECT_APP_EXIST.toErrorCode());
        // }

        String appSecret = "12365478987654321";
        String url = request.getRequestURL().toString();

        //3、校验签名
        String signature = DigestUtils.md5DigestAsHex(("POST" + url + data + appSecret).getBytes());
        logger.info("upload platform get the md5 signature result :{}",signature);
        if (!signature.equals(sign)){
            return ResultUtil.success("APP_SIGNATURE_ERROR");
        }

        //4、处理业务数据

        return ResultUtil.success();
    }

    private Map showParams(HttpServletRequest request) {
        Map map=new HashMap();
        Enumeration paramNames=request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String paramName=(String) paramNames.nextElement();
            String[] paramValues=request.getParameterValues(paramName);
            if (paramValues.length==1) {
                String paramValue=paramValues[0];
                if (paramValue.length() !=0) {
                    map.put(paramName, paramValue);
                }
            }
        }
        return map;
    }

    public static String saveImageLocal(MultipartFile mfile,String prefix){
        File toFile = null;
        if (mfile!=null && mfile.getSize()>0) {
            //获取文件原名称
            String originalFilename = mfile.getOriginalFilename();
            //获取文件格式
            String fileFormat = originalFilename.substring(originalFilename.lastIndexOf("."));

            //转file   生成随机文件名 （File.separator : 作用相当于 '\'）
            String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
            toFile = new File("E:\\测试文件\\saveLocal\\image"+File.separator+prefix+uuid+fileFormat);
            //最终绝对路径
            String absolutePath = null;

            try {
                //获取绝对路径  并去除[..]这样的符号，返回的是标准的绝对路径
                absolutePath = toFile.getCanonicalPath();

                //判断路径中的文件夹是否存在，如果不存在，则先创建文件夹
                String dirPath = absolutePath.substring(0, absolutePath.lastIndexOf(File.separator));
                File dir = new File(dirPath);
                if (!dir.exists()){
                    dir.mkdirs();
                }

                InputStream ins = mfile.getInputStream();
                inputStreamToFile(ins,toFile);
                ins.close();

                return toFile.getAbsolutePath();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
